import axios from 'axios'
export default {
  namespaced: true,
  state () {
    return {
      list: []
    }
  },
  mutations: {
    updataList (state, payload) {
      state.list = payload
    },
    updateCount (state, obj) {
      const goods = state.list.find((item) => item.id === obj.id)
      goods.count = obj.count
    }
  },
  actions: {
    async getList (context) {
      const res = await axios.get('http://localhost:3000/cart')
      // console.log(res)
      context.commit('updataList', res.data)
    },
    async getNewCount (context, obj) {
      await axios.patch('http://localhost:3000/cart/' + obj.id, {
        count: obj.count
      })
      // console.log(res)
      context.commit('updateCount', obj)
    }
  },
  getters: {
    allCount (state) {
      return state.list.reduce((sum, item) => sum + item.count, 0)
    },
    allPrice (state) {
      return state.list.reduce((sum, item) => sum + item.count * item.price, 0)
    }
  }
}
